﻿using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Description;

namespace Sharp.Infrastructure.WCF
{
    public class HttpBindingServiceHostFactory : WebServiceHostFactory
    {
        private static readonly ConcurrentDictionary<Type, Type> ServiceContracts;
        private static readonly WSHttpBinding Binding;
        static HttpBindingServiceHostFactory()
        {
            ServiceContracts = new ConcurrentDictionary<Type, Type>();
            Binding = new WSHttpBinding("wsServiceProxyBinding");

        }
        protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
        {
            var host = base.CreateServiceHost(serviceType, baseAddresses);


            Type implementedContract = ServiceContracts.GetOrAdd(serviceType, (t) =>
             {//把契约缓存起来
                var contracts =
                     ((TypeInfo)serviceType).ImplementedInterfaces.Single(y => y != typeof(IApplicationServiceContract));

                 return contracts;
             });

            ServiceEndpoint se = host.AddServiceEndpoint(implementedContract, Binding, "");
            se.Behaviors.Add(new ContextPropagationBehavior());


            return host;
        }
    }

}
